<?php
/**
 * Created by PhpStorm.
 * User: qhzhyt
 * Date: 2018/10/23
 * Time: 22:39
 */
require_once '../conf/conf.php';
function sendVerifyMail($sendTo, $verifyCode)
{
    global $gameName, $rootUrl;
    require_once("../conf/smtp_conf.php");
    $content = "亲爱的" . $gameName . "用户：<br/>您正在重置登录密码请点击以下链接继续操作。<br/><a href='{$rootUrl}resetPassword.php?verifyCode=" . $verifyCode . "' target='_blank'>{$rootUrl}resetPassword.php?verifyCode=" . $verifyCode . "</a><br/>如果以上链接无法点击，请将它复制到你的浏览器地址栏中进入访问，该链接24小时内有效。<br/>如果此次激活请求非你本人所发，请忽略本邮件。<br/><p style='text-align:right'>-------- TouHouMaker 敬上</p>";
    return sendMail("重置密码", $content, $sendTo, $sendTo, $gameName);
}

if (!isset($_POST['email'])) {
    echo(json_encode(['status' => 0, 'code' => 2]));
    exit(1);
}

$email = $_POST['email'];

$user = $db->get('user', '*', ['email' => $email]);

if ($user == null) {
    echo(json_encode(['status' => 0, 'code' => 5]));
    exit(1);
}

$record = $db->get('email_record', '*', ['user_id' => $user['user_id']]);

if ($record != null && strtotime($record['send_time']) + 24 * 60 * 60 > time()) {
    //$log->addDebug($record['send_time']);
    $db->delete('email_record',['verify_code' => $record['verify_code']]);
}

$verifyCode = md5(time() . $user['user_id'] . random_int(0, 999999));

if (sendVerifyMail($email, $verifyCode)) {
    $db->insert('email_record', ['user_id' => $user['user_id'], 'verify_code' => $verifyCode]);
    if ($db->id() == null) {
        echo(json_encode(['status' => 0, 'code' => 0]));
        exit(1);
    }
    echo(json_encode(['status' => 1, 'code' => 1]));
    exit(1);
} else {
    echo(json_encode(['status' => 0, 'code' => 0]));
    exit(1);
}